package com.babai.controller.platform;

import com.babai.common.Result;
import com.babai.entity.platform.PlatformScript;
import com.babai.service.platform.PlatformScriptService;
import com.babai.util.DateUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/platform/script")
public class PlatformScriptController {

    @Autowired
    private PlatformScriptService platformScriptService;


    @RequestMapping(value = "/form", method = RequestMethod.GET)
    public ModelAndView form(@RequestParam(required = false) String id) {
        ModelAndView mv = new ModelAndView("form");
        if (StringUtils.isNotBlank(id)) {
            mv.addObject("id", id);
        }
        return mv;
    }

    @RequestMapping(value = "/formView", method = RequestMethod.GET)
    public ModelAndView formView(@RequestParam(required = false) String id) {
        ModelAndView mv = new ModelAndView("form_view");
        if (StringUtils.isNotBlank(id)) {
            mv.addObject("id", id);
        }
        return mv;
    }

    @RequestMapping(path = "/list", method = RequestMethod.POST)
    public Result list() {
        List<PlatformScript> list = platformScriptService.findAll(Sort.by(Sort.Direction.ASC, "sortNo"));
        return Result.success().addData(list);
    }

    @RequestMapping(path = "/save", method = RequestMethod.POST)
    public Result save(@RequestBody PlatformScript paramObject) {
        PlatformScript entity;
        if (StringUtils.isBlank(paramObject.getId())) {// 新增
            entity = paramObject;
        } else {// 更新
            entity = platformScriptService.findById(paramObject.getId());
            String[] ignoreProperties = {"id"};
            BeanUtils.copyProperties(paramObject, entity, ignoreProperties);
        }
        platformScriptService.saveOrUpdate(entity);
        return Result.success();
    }

    @RequestMapping(path = "/delete", method = RequestMethod.POST)
    public Result delete(@RequestBody PlatformScript paramEntity) {
        platformScriptService.deleteById(paramEntity.getId());
        return Result.success();
    }

    @RequestMapping(path = "/load", method = RequestMethod.POST)
    public Result load(@RequestBody PlatformScript paramEntity) {
        PlatformScript entity = platformScriptService.findById(paramEntity.getId());
        return Result.success().addData(entity);
    }

    @RequestMapping(path = "/generate", method = RequestMethod.POST)
    public Result generate(@RequestBody PlatformScript paramEntity) {
        String generatePath = paramEntity.getGeneratePath();
        File generateFolder = new File(generatePath);
        if (!generateFolder.exists()) {
            generateFolder.mkdirs();
        }

        String versionFolderStr = DateUtil.HHmmss();
        File versionFolder = new File(generateFolder, versionFolderStr);
        if (!versionFolder.exists()) {
            versionFolder.mkdirs();
        }

        String preDB6FolderStr = "01_PRE_PUPSDB6";
        String preDB8FolderStr = "01_PRE_PUPSDB8";
        String preDB9FolderStr = "01_PRE_PUPSDB9";
        String preDB12FolderStr = "01_PRE_PUPSDB12";
        String preDB13FolderStr = "01_PRE_PUPSDB13";
        String preDB19FolderStr = "01_PRE_PUPSDB19";
        String db6FolderStr = "PUPSDB6";
        String db8FolderStr = "PUPSDB8";
        String db9FolderStr = "PUPSDB9";
        String db12FolderStr = "PUPSDB12";
        String db13FolderStr = "PUPSDB13";
        String db19FolderStr = "PUPSDB19";
        int jiraIndex = 1;
        List<PlatformScript> list = platformScriptService.findAll(Sort.by(Sort.Direction.ASC, "sortNo"));
        try {
            for (PlatformScript platformScript : list) {
                String jiraNumber = platformScript.getJiraNumber();
                String fileName = "P" + String.format("%03d", jiraIndex) + "-" + jiraNumber + ".sql";
                generateFile(versionFolder, preDB6FolderStr, fileName, platformScript.getPreDB6());
                generateFile(versionFolder, preDB8FolderStr, fileName, platformScript.getPreDB8());
                generateFile(versionFolder, preDB9FolderStr, fileName, platformScript.getPreDB9());
                generateFile(versionFolder, preDB12FolderStr, fileName, platformScript.getPreDB12());
                generateFile(versionFolder, preDB13FolderStr, fileName, platformScript.getPreDB13());
                generateFile(versionFolder, preDB19FolderStr, fileName, platformScript.getPreDB19());
                generateFile(versionFolder, db6FolderStr, fileName, platformScript.getDb6());
                generateFile(versionFolder, db8FolderStr, fileName, platformScript.getDb8());
                generateFile(versionFolder, db9FolderStr, fileName, platformScript.getDb9());
                generateFile(versionFolder, db12FolderStr, fileName, platformScript.getDb12());
                generateFile(versionFolder, db13FolderStr, fileName, platformScript.getDb13());
                generateFile(versionFolder, db19FolderStr, fileName, platformScript.getDb19());
                jiraIndex++;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success().addData(versionFolder.getAbsolutePath());
    }

    public void generateFile(File versionFolder, String dbFolderStr, String fileName, String script) throws IOException {
        if (StringUtils.isNotBlank(script)) {
            File dbFolder = new File(versionFolder, dbFolderStr);
            if (!dbFolder.exists()) {
                dbFolder.mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(new File(dbFolder, fileName));
            IOUtils.write(script.getBytes(StandardCharsets.UTF_8), fos);
            IOUtils.closeQuietly(fos);
        }
    }

}
